// src/index.ts
import { evaluate } from "./evaluator";
import { tokenize } from "./lexer";
import { parse } from "./parser";
import print from "./print";

/**
 * @description 模版计算
 * @param tpl 'a+b+floor(a*c)'
 * @param data {a:1,b:2,c:3}
 * ```
 * import {renderTemplate} from '@syzlm/evaluator';
 * renderTemplate('a+b+floor(a*c)', {a:1,b:2,c:3})
 * ```
 * @returns
 */
export const renderTemplate = (
  tpl: string,
  data: { [k: string]: string | number }
): string => {
  try {
    const tokens = tokenize(tpl, data);
    if (tokens?.length) {
      print.info("tokens:", tokens);
      const ast = parse(tokens);
      print.info("ast:", ast);
      const result = evaluate(ast);
      return result;
    }
    return "";
  } catch (error: any) {
    print.error("error:", error);
    return `Error: ${error?.message || ""}`;
  }
};
/**
 * @description 精确四舍五入
 * ```
 * import {toFixeds} from '@syzlm/evaluator';
 * toFixeds('121.003929323112',12)
 * toFixeds('121.003929323112',3,15)
 * ```
 */
export { toFixeds } from "./bigNumber";
export {
  /**
   * @description 精确加法
   * ```
   * import {evaluatorAdd} from '@syzlm/evaluator';
   * evaluatorAdd('121.003929323112','12')
   * ```
   */
  add as evaluatorAdd,
  /**
   * @description 精确减法
   * ```
   * import {evaluatorSubtract} from '@syzlm/evaluator';
   * evaluatorSubtract('121.003929323112','12')
   * ```
   */
  subtract as evaluatorSubtract,
  /**
   * @description 精确✖️法
   * ```
   * import {evaluatorMultiply} from '@syzlm/evaluator';
   * evaluatorMultiply('121.003929323112','12')
   * ```
   */
  multiply as evaluatorMultiply,
  /**
   * @description 精确除法
   * ```
   * import {evaluatorDivide} from '@syzlm/evaluator';
   * evaluatorDivide('121.003929323112','12')
   * ```
   */
  divide as evaluatorDivide,
} from "./bigNumber";
/** debug 开启配置 */
export { setOptions } from "./print";

export default renderTemplate;
